package com.douwong.student.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.douwong.student.application.BaseApplication;
import com.douwong.student.model.PrepareResource;
import com.douwong.student.utils.LogUtils;
import com.douwong.student.utils.TimeUtils;

import java.util.ArrayList;


/**
 * 记录备课资源
 * 
 * @author leihuajie
 * 
 */
public class PrepareReaourceDBService extends BDBaseService<PrepareResource> {

	private static final String TAG = PrepareReaourceDBService.class.getSimpleName();

	protected PrepareReaourceDBService(Context context) {
		super(context);
	}

	// private static PrepareReaourceDBService prepareResourceDBService = null;
	// 单例模式 造成数据库 连接池异常问题
	public static PrepareReaourceDBService getInstance(Context context) {
		// if (prepareResourceDBService == null) {
		// prepareResourceDBService = new PrepareReaourceDBService(context);
		// }
		return new PrepareReaourceDBService(context);
	}

	@Override
	public void add(PrepareResource t) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.execSQL(
				"insert into prepare_resource(fileName,fileSize,subject,userName,createTime,userId,suffixType,loadUrl,attaKey,fileId,attaSuffix) values (?,?,?,?,?,?,?,?,?,?,?)",
				new Object[] { t.getFileName(), t.getFileSize(), t.getSubjectName(), t.getUserName(), t.getCreatetime(),
						BaseApplication.sUserBean.getUserbean().getEuNumber(), t.getSuffixType(), t.getDownLoadUrl(),
						t.getAttaKey(), t.getId(), t.getAttaSuffix() });
		
		db.close();
	}

	public void addLoading(PrepareResource t) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.execSQL(
				"insert into prepare_load(fileName,fileSize,subject,userName,createTime,userId,suffixType,loadUrl,attaKey,isLoading,fileId,filePath,attaSuffix,mcTitle) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
				new Object[] { t.getFileName(), t.getFileSize(), t.getSubjectName(), t.getUserName(), t.getCreatetime(),
						BaseApplication.sUserBean.getUserbean().getEuNumber(), t.getSuffixType(), t.getDownLoadUrl(),
						t.getAttaKey(), t.isLoading() == true ? 1 : 0, t.getId(), t.getFilePath(), t.getAttaSuffix(),t.getMcTitle()});
		db.close();
	}

	// 查询资源列表

	public ArrayList<PrepareResource> queryResource(int fileType) {
		Cursor cursor = null;
		ArrayList<PrepareResource> list = new ArrayList<PrepareResource>();
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		if (fileType == 0) {
			cursor = db.rawQuery("select * from prepare_resource where userId=?",
					new String[] { BaseApplication.sUserBean.getUserbean().getEuNumber() });
		} else {
			cursor = db.rawQuery("select * from prepare_resource where userId=? and suffixType=?",
					new String[] { BaseApplication.sUserBean.getUserbean().getEuNumber(), String.valueOf(fileType) });
		}
		if (cursor != null) {
			while (cursor.moveToNext()) {
				PrepareResource pr = new PrepareResource();
				pr.setFileName(cursor.getString(1));
				pr.setFileSize(cursor.getLong(2));
				pr.setSubjectName(cursor.getString(3));
				pr.setUserName(cursor.getString(4));
				pr.setCreatetime(cursor.getString(5));
				pr.setSuffixType(cursor.getInt(11));
				pr.setAttaKey(cursor.getString(13));
				pr.setLoaded(cursor.getInt(8) == 1 ? true : false);
				pr.setLoading(cursor.getInt(7) == 1 ? true : false);
				pr.setDownLoadUrl(cursor.getString(12));
				pr.setId(cursor.getInt(15));
				pr.setAttaSuffix(cursor.getString(16));
				pr.setFilePath(cursor.getString(14));
				list.add(pr);
			}
			cursor.close();
		}

		db.close();
		return list;

	}
	// 查询已下载列表

	public ArrayList<PrepareResource> queryLoaded(int fileType) {
		Cursor cursor = null;
		ArrayList<PrepareResource> list = new ArrayList<PrepareResource>();
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		if (fileType == 0) {
			cursor = db.rawQuery("select * from prepare_load where userId=? and isLoaded=1 order by loadTime desc",
					new String[] { BaseApplication.sUserBean.getUserbean().getEuNumber() });
		} else {
			cursor = db.rawQuery("select * from prepare_load where userId=? and suffixType=? and isLoaded=1",
					new String[] { BaseApplication.sUserBean.getUserbean().getEuNumber(), String.valueOf(fileType) });
		}
		if (cursor != null) {
			while (cursor.moveToNext()) {
				PrepareResource pr = new PrepareResource();
				pr.setFileName(cursor.getString(1));
				pr.setFileSize(cursor.getLong(2));
				pr.setSubjectName(cursor.getString(3));
				pr.setUserName(cursor.getString(4));

				if (cursor.getString(20)==null){
					pr.setCreatetime(cursor.getString(5));//5
				}else {
					pr.setCreatetime(cursor.getString(20));//5
				}

				pr.setSuffixType(cursor.getInt(11));
				pr.setAttaKey(cursor.getString(13));
				pr.setLoading(cursor.getInt(7) == 1 ? true : false);
				pr.setLoaded(cursor.getInt(8) == 1 ? true : false);
				pr.setFilePath(cursor.getString(14));
				pr.setId(cursor.getInt(16));
				pr.setAttaSuffix(cursor.getString(18));
				pr.setMcTitle(cursor.getString(19));
				list.add(pr);
			}
			cursor.close();
		}

		db.close();
		return list;

	}

	// 跟新资源列表狀態
	public void upDate(PrepareResource pr) {
		Log.e("upDate", "开始更新");
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		try {
			db.execSQL("update prepare_resource set isLoading=?,isLoaded=?,filePath=? where userId=? and fileId=?",
					new Object[] { pr.isLoading() == true ? 1 : 0, pr.isLoaded() == true ? 1 : 0, pr.getFilePath(),
							BaseApplication.sUserBean.getUserbean().getEuNumber(), pr.getId() });
		} catch (Exception e) {
			e.printStackTrace();
		}
		db.close();
	}

	// 跟新正在下载
	public void upDateLoading(PrepareResource pr) {
		Log.e("upDate", "开始更新");
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		try {
			db.execSQL(
					"update prepare_load set isLoading=?,isLoaded=?,isPause=?,currentPro=? where userId=? and fileId=?",
					new Object[] { pr.isLoading() == true ? 1 : 0, pr.isLoaded() == true ? 1 : 0,
							pr.isPause() == true ? 1 : 0, pr.getCurrentPro(),
							BaseApplication.sUserBean.getUserbean().getEuNumber(), pr.getId()});


		} catch (Exception e) {
			e.printStackTrace();
		}
		db.close();
	}

	/**
	 * 添加下载成功时间
     */
	public void upDateLoadTime(PrepareResource pr){
		LogUtils.i(TAG,"更新下载时间");
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		try {
			db.execSQL(
					"update prepare_load set loadTime=? where userId=? and fileId=?",
					new Object[] {TimeUtils.getTime(),
							BaseApplication.sUserBean.getUserbean().getEuNumber(), pr.getId()});


		} catch (Exception e) {
			e.printStackTrace();
		}
		LogUtils.i(TAG,"更新下载时间成功");
		db.close();

	}

	// 跟新系在资源的总大小
	public void updateSize(int id, long totalSize) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.execSQL("update prepare_load set totalSize=? where userId=? and fileId=?",
				new Object[] { totalSize, BaseApplication.sUserBean.getUserbean().getEuNumber(), id });
		db.close();
	}

	// 查询资源总大小
	public long queryTotalSize(int id) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		long totalSize = 0;
		Cursor cursor = db.rawQuery("select * from prepare_load where fileId=? and userId=?",
				new String[] { String.valueOf(id), BaseApplication.sUserBean.getUserbean().getEuNumber() });
		if (cursor.moveToFirst()) {
			totalSize = cursor.getLong(17);
			cursor.close();
		}
		db.close();
		return totalSize;
	}

	// 查询正在下载列表

	public ArrayList<PrepareResource> queryLoading() {
		Cursor cursor = null;
		ArrayList<PrepareResource> list = new ArrayList<PrepareResource>();
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		cursor = db.rawQuery("select * from prepare_load where isLoading=1 and userId=?",
				new String[] { BaseApplication.sUserBean.getUserbean().getEuNumber() });
		if (cursor != null) {
			while (cursor.moveToNext()) {
				PrepareResource pr = new PrepareResource();
				pr.setFileName(cursor.getString(1));
				pr.setFileSize(cursor.getLong(2));
				pr.setSubjectName(cursor.getString(3));
				pr.setUserName(cursor.getString(4));
				pr.setCreatetime(cursor.getString(5));
				pr.setSuffixType(cursor.getInt(11));
				pr.setAttaKey(cursor.getString(13));
				pr.setDownLoadUrl(cursor.getString(12));
				pr.setId(cursor.getInt(16));
				pr.setPause(cursor.getInt(9) == 1 ? true : false);
				pr.setFilePath(cursor.getString(14));
				pr.setCurrentPro(cursor.getLong(6));
				pr.setAttaSuffix(cursor.getString(18));
				/*----start----*/
				pr.setMcTitle(cursor.getString(19));//设置文件名
				/*-----end--------*/
				list.add(pr);
			}
			cursor.close();
		}

		db.close();
		return list;

	}

	@Override
	public void delete(int id) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.execSQL("delete from prepare_resource where userId=? and suffixType=?",
				new String[] { BaseApplication.sUserBean.getUserbean().getEuNumber(), String.valueOf(id) });
		db.close();
	}

	public void deleteResource(int id) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.execSQL("delete from prepare_resource where userId=? and fileId=?",
				new String[] { BaseApplication.sUserBean.getUserbean().getEuNumber(), String.valueOf(id) });
		db.close();
	}

	public void deleteLoading(int id) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.execSQL("delete from prepare_load where userId=? and fileId=?",
				new String[] { BaseApplication.sUserBean.getUserbean().getEuNumber(), String.valueOf(id) });
		db.close();
	}

	@Override
	public void update(int id) {

	}

	@Override
	public PrepareResource query(int id) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		PrepareResource prepareResource = null;
		Cursor cursor = db.rawQuery("select * from prepare_load where userId=? and fileId=?",
				new String[] { BaseApplication.sUserBean.getUserbean().getEuNumber(), String.valueOf(id) });
		if (cursor.moveToFirst()) {
			prepareResource = new PrepareResource();
			prepareResource.setFilePath(cursor.getString(14));
			prepareResource.setLoading(cursor.getInt(7) == 1 ? true : false);
			prepareResource.setLoaded(cursor.getInt(8) == 1 ? true : false);
			cursor.close();
		}
		db.close();
		return prepareResource;
	}

}
